/*    file: main.cpp
 *    desc:
 * 
 * created: 2016-04-06
 *  author: chuanjiang.zh@qq.com
 * company: 
 */

#include <stdio.h>
#include <iostream>

#include "CApplication.h"

#include "BasicType.h"
#include "TFileUtil.h"
#include "TByteBuffer.h"
#include <assert.h>
#include <errno.h>

#include "UMediaFileConverter.h"
#include "Path.h"


class ConvApplication : public CApplication, public UMediaFileConverterSink
{
public:
	ConvApplication()
	{
		UMediaFileConverterFactory::startup();
	}

	~ConvApplication()
	{
		UMediaFileConverterFactory::cleanup();
	}

	virtual void onConvert(UMediaFileConverter* converter, int state, int64_t time, double percent)
	{
		printf("convert progress. state:%d, time: %lld ms, pos:%.2f\n", state, time/1000, percent);

		if (state == UMEDIA_CONVERTER_END || state == UMEDIA_CONVERTER_ERROR)
		{
			int64_t convDuration = converter->getConvertDuration() / 1000;
			int64_t convElapse = converter->getConvertElapse();
			
			printf("convert done. duration: %lld s, elapse: %lld ms\n", convDuration, convElapse);

			exit();
		}
	}

	int setPath(const std::string& inPath, const std::string& outPath)
	{
		m_converter.reset(UMediaFileConverterFactory::create(""), UMediaFileConverterFactory::destroy);

		m_converter->setSink(this);

		int ret = m_converter->open(inPath.c_str(), outPath.c_str());
		return ret;
	}

	virtual bool init()
	{
		m_converter->start();

		return true;
	}


	std::shared_ptr<UMediaFileConverter> m_converter;

};

typedef std::shared_ptr< UMediaFileConverter >	FileConverterPtr;


void usage()
{
	std::cout << "UFileConv input_file output_file" << std::endl;
}

int main(int argc, char** argv)
{
	std::string inPath;
	std::string outPath;

	if (argc < 3)
	{
		usage();
		return EINVAL;
	}

	inPath = argv[1];
	outPath = argv[2];

	if (!comn::Path::exist(inPath))
	{
		return ENOENT;
	}

	ConvApplication app;

	int ret = app.setPath(inPath, outPath);
	if (ret != 0)
	{
		return ret;
	}

	app.launch(argc, argv);

	return EXIT_SUCCESS;
}




